##https://om0813.zw7gmc49.work/api/user/account/login
##{"account":"wangyukunop","password":"zxw123456","deviceId":"h5_40d13882_1af1_4833_ad08_29351"}
##post提交
from 核心.配置文件 import settings
from 核心.解密数据 import vp
import requests,json,time

def extract_token_from_data(data):
    try:
        if isinstance(data, dict):
            # 直接从响应中查找token
            if 'token' in data:
                return data['token']

            # 如果响应中有data字段，从data中查找
            if 'data' in data and isinstance(data['data'], dict):
                if 'token' in data['data']:
                    return data['data']['token']

        return None
    except Exception as e:
        print(f"提取token失败: {e}")
        return None
def get_token():
    url = f"{settings.BASE_URL}/api/user/account/login"
    payload = {"account": "wangyukunop", "password": "zxw123456", "deviceId": "h5_40d13882_1af1_4833_ad08_29351"}

    # 使用动态时间戳
    current_timestamp = int(time.time() * 1000)

    headers = {
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'authorization': 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMTYzMTA3NyIsImlzcyI6IiIsImlhdCI6MTc1NjE5MTQyNCwibmJmIjoxNzU2MTkxNDI0LCJleHAiOjE5MTM4NzE0MjR9.31GlXOHvBEjKqJlvcdYmtxH6tR88ua0Z3Yf77ig9M9U',
        'cache-control': 'no-cache',
        'deviceid': 'h5_a5be7aa1_850a_469b_8f94_40892',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        's': '7c4797ad736d4598201ba34250d17c99',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        't': str(current_timestamp),  # 使用动态时间戳
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
        'user-mark': 'xhp'
    }

    try:
        print(f"正在发送登录请求到: {url}")
        print(f"使用时间戳: {current_timestamp}")

        # 使用json参数而不是data参数，这样会自动设置正确的Content-Type
        response = requests.request("POST", url, headers=headers, json=payload, timeout=30)

        print(f"响应状态码: {response.status_code}")
        print(f"响应头: {dict(response.headers)}")

        if response.status_code != 200:
            print(f"HTTP请求失败，状态码: {response.status_code}")
            print(f"响应内容: {response.text}")
            return None

        try:
            data = response.json()
            print(f"JSON解析成功: code={data.get('code')}, msg={data.get('msg')}")
            # 解密并保存数据
            decrypted_data = vp(data['encData'])
            # 提取token
            token = extract_token_from_data(decrypted_data)
            if token:
                print(f"✅ 成功获取token: {token[:20]}...")
                return token
            else:
                print("⚠️ 未找到token")
                return decrypted_data

        except json.JSONDecodeError as json_error:
            print(f"JSON解析失败: {json_error}")
            print(f"响应内容: {response.text}")
            return None

    except requests.exceptions.Timeout:
        print("请求超时，请检查网络连接或稍后重试")
        return None
    except requests.exceptions.RequestException as e:
        print(f"HTTP请求失败: {e}")
        return None
    except Exception as e:
        print(f"登录过程中发生未知错误: {e}")
        return None


if __name__ == "__main__":
    get_token()